package com.self.cgqcompose.ui.components.areacode

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import coil.compose.AsyncImage
import com.self.cgqcompose.beans.AreaBlock
import com.self.cgqcompose.common.ConstantsUi
import com.self.cgqcompose.mock.MockJson

/**2x2 横图*/
@Composable
fun AreaCode120(data: AreaBlock) {
    val items = data.data.children[0].data
    val rows = items.chunked(2) // 每两项为一行

    Column(
        modifier = Modifier
            .padding(horizontal = ConstantsUi.HOME_MARGIN),
        verticalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        BlockTitle(data)
        rows.forEach { rowItems ->
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(ConstantsUi.HOME_ITEM_SPACING)
            ) {
                rowItems.forEach { item ->
                    Column(
                        modifier = Modifier
                            .weight(1f)
                    ) {
                        AsyncImage(
                            model = item.cover,
                            contentDescription = null,
                            modifier = Modifier
                                .fillMaxWidth()
                                .aspectRatio(16 / 9f)
                                .clip(RoundedCornerShape(5.dp)),
                            contentScale = ContentScale.Crop
                        )
                        Text(text = item.title, fontSize = 14.sp)
                        Text(text = item.aspect, fontSize = 12.sp, color = Color(0xFF8D979F),
                            lineHeight = 12.sp)
                    }
                }

                // 如果这一行只有一个元素，补一个空 Box 占位以对齐右边
                if (rowItems.size < 2) {
                    Spacer(modifier = Modifier.weight(1f))
                }
            }
        }
    }
}

@Preview(showBackground = true, backgroundColor = 0xffffffff)
@Composable
fun AreaCode120Preview() {
    val context = LocalContext.current;
    val area9 = MockJson.loadMockDataArea9(context)
    AreaCode120(area9.data[2])
}